<template>
  <div class="order-add-container">
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">订单详情</h2>
        <el-button icon="el-icon-back" @click="$router.go(-1)">返回</el-button>
      </div>
      <div class="total-points" v-if="isView">消耗积分：{{ calculateOrderTotal() }} 分</div>
    </div>

    <div class="content-container">
      <!-- 订单基本信息 -->
      <div class="section-card">
        <div class="section-header">
          <h3>订单基本信息</h3>
        </div>
        <el-form
          ref="orderForm"
          :model="form"
          :rules="rules"
          label-width="100px"
          :disabled="isView"
        >
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="订单编号" prop="orderNo" v-if="isView">
                <el-input v-model="form.orderNo" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="下单时间" prop="createTime" v-if="isView">
                <el-input v-model="form.createTime" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="用户名" prop="userId">
                <el-select v-model="form.userId" filterable placeholder="请选择用户">
                  <el-option
                    v-for="item in userOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                    <span>{{ item.label }}</span>
                    <span class="user-id">ID: {{ item.id }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="订单状态" prop="status" v-if="isView">
                <el-select v-model="form.status" placeholder="请选择订单状态">
                  <el-option
                    v-for="item in statusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 订单商品明细 -->
      <div class="section-card">
        <div class="section-header">
          <h3>订单商品明细</h3>
          <el-button
            type="primary"
            plain
            size="small"
            @click="showAddProductDialog"
            v-if="!isView"
          >添加商品</el-button>
        </div>
        <div class="product-list">
          <el-table :data="form.products" border style="width: 100%">
            <el-table-column type="index" label="序号" width="80"></el-table-column>
            <el-table-column prop="productName" label="商品名称" min-width="180">
              <template slot-scope="scope">
                <div>
                  {{ scope.row.productName }}
                  <div v-if="scope.row.skuSpecs" class="sku-specs">
                    <el-tag
                      size="mini"
                      v-for="(value, key) in scope.row.skuSpecs"
                      :key="key"
                      style="margin-right: 5px"
                    >{{ key }}: {{ value }}</el-tag>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="120"></el-table-column>
            <el-table-column prop="points" label="单价(积分)" width="120">
              <template slot-scope="scope">
                <span>{{ scope.row.points }} 分</span>
              </template>
            </el-table-column>
            <el-table-column prop="totalPoints" label="小计(积分)" width="120">
              <template slot-scope="scope">
                <span>{{ scope.row.totalPoints }} 分</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" v-if="!isView">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="removeProduct(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="order-total" v-if="!isView">
            <span>订单总积分：</span>
            <span class="total-points">{{ calculateOrderTotal() }} 分</span>
          </div>
        </div>
      </div>

      <!-- 收货信息 -->
      <div class="section-card">
        <div class="section-header">
          <h3>收货信息</h3>
        </div>
        <el-form
          ref="orderForm"
          :model="form"
          :rules="rules"
          label-width="100px"
          :disabled="isView"
        >
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="收货人" prop="receiver">
                <el-input v-model="form.receiver" placeholder="请输入收货人姓名"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系电话" prop="phone">
                <el-input v-model="form.phone" placeholder="请输入联系电话"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16">
              <el-form-item label="收货地址" prop="address">
                <el-input type="textarea" v-model="form.address" :rows="3" placeholder="请输入收货地址"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16">
              <el-form-item label="备注" prop="remark">
                <el-input type="textarea" v-model="form.remark" :rows="3" placeholder="请输入备注信息"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 底部按钮 -->
      <div class="bottom-actions" v-if="!isView">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="resetForm">重置</el-button>
      </div>
    </div>

    <!-- 添加商品弹窗 -->
    <el-dialog title="添加商品" :visible.sync="dialogVisible" width="600px">
      <el-form :model="productForm" label-width="80px">
        <el-form-item label="商品">
          <el-select
            v-model="productForm.productId"
            filterable
            placeholder="请选择商品"
            @change="handleDialogProductChange"
          >
            <el-option
              v-for="item in productOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
              <div class="product-option">
                <span>{{ item.label }}</span>
                <span class="product-points">{{ item.points }} 积分</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 选择SKU规格 -->
        <el-form-item
          label="规格"
          v-if="selectedProduct && selectedProduct.skus && selectedProduct.skus.length > 0"
        >
          <el-select
            v-model="productForm.skuId"
            filterable
            placeholder="请选择规格"
            @change="handleSkuChange"
          >
            <el-option
              v-for="item in selectedProduct.skus"
              :key="item.id"
              :label="skuSpecsToText(item.specs)"
              :value="item.id"
            >
              <div class="product-option">
                <span>{{ skuSpecsToText(item.specs) }}</span>
                <span class="product-points">{{ item.price }} 积分</span>
              </div>
            </el-option>
          </el-select>
          <div class="stock-info" v-if="selectedSku">
            <span>可用库存: {{ selectedSku.availableStock }}</span>
          </div>
        </el-form-item>

        <el-form-item label="数量">
          <el-input-number v-model="productForm.quantity" :min="1" :max="getMaxQuantity()"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAddProduct">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addOrder, getOrderDetail, updateOrder } from '@/api/order'
import { getProductList } from '@/api/product'
import { getUserList } from '@/api/user'

export default {
  name: 'OrderAdd',
  data() {
    return {
      isEdit: false,
      isView: false,
      dialogVisible: false,
      loading: false,
      form: {
        id: null,
        orderNo: '',
        createTime: '',
        userId: '',
        username: '',
        status: '待付款',
        receiver: '',
        phone: '',
        address: '',
        remark: '',
        products: [],
      },
      selectedProduct: null,
      selectedSku: null,
      productForm: {
        productId: '',
        skuId: '',
        quantity: 1,
      },
      rules: {
        userId: [{ required: true, message: '请选择用户', trigger: 'change' }],
        receiver: [
          { required: true, message: '请输入收货人姓名', trigger: 'blur' },
        ],
        phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
        address: [
          { required: true, message: '请输入收货地址', trigger: 'blur' },
        ],
      },
      userOptions: [],
      productOptions: [],
      statusOptions: [
        { value: '待付款', label: '待付款' },
        { value: '待发货', label: '待发货' },
        { value: '已发货', label: '已发货' },
        { value: '已完成', label: '已完成' },
        { value: '已取消', label: '已取消' },
      ],
    }
  },
  created() {
    this.loadUserOptions()
    this.loadProductOptions()

    // 获取路由参数，判断是查看还是新增
    const id = this.$route.query.id
    if (id) {
      this.isEdit = true
      this.isView = true
      this.fetchOrderDetail(id)
    }
  },
  methods: {
    // 加载用户选项
    loadUserOptions() {
      getUserList({ limit: 100 })
        .then(res => {
          if (res.code === 200 && res.data.list) {
            this.userOptions = res.data.list.map(user => ({
              id: user.id,
              value: user.id,
              label: user.nickname || user.username,
              points: user.points,
            }))
          }
        })
        .catch(error => {
          console.error('获取用户列表出错', error)
          this.$message.error('获取用户列表失败')
        })
    },
    // 加载商品选项
    loadProductOptions() {
      getProductList({ limit: 100, status: '在售' })
        .then(res => {
          if (res.code === 200 && res.data.list) {
            this.productOptions = res.data.list.map(product => ({
              value: product.id,
              label: product.name,
              points: product.price,
              stock: product.stock,
              data: product,
            }))
          }
        })
        .catch(error => {
          console.error('获取商品列表出错', error)
          this.$message.error('获取商品列表失败')
        })
    },
    // 商品变更事件
    handleProductChange(val) {
      const selectedProduct = this.productOptions.find(
        item => item.value === val
      )
      if (selectedProduct) {
        this.form.points = selectedProduct.points
        this.calculateTotal()
      }
    },
    // 计算总积分
    calculateTotal() {
      this.form.totalPoints = this.form.points * this.form.quantity
    },
    // 表单提交
    submitForm() {
      this.$refs.orderForm.validate(valid => {
        if (valid) {
          if (this.form.products.length === 0) {
            this.$message.warning('请至少添加一个商品')
            return false
          }

          this.loading = true

          // 准备请求数据
          const selectedUser = this.userOptions.find(
            user => user.value === this.form.username
          )

          const orderData = {
            userId: selectedUser ? selectedUser.id : 0,
            items: this.form.products.map(product => ({
              productId: product.productId,
              quantity: product.quantity,
            })),
            receiver: this.form.receiver,
            phone: this.form.phone,
            address: this.form.address,
            remark: this.form.remark,
          }

          const request = this.isEdit
            ? updateOrder(this.form.id, orderData)
            : addOrder(orderData)

          request
            .then(res => {
              if (res.code === 200) {
                this.$message.success(this.isEdit ? '编辑成功' : '新增成功')
                this.$router.push('/order/list')
              } else {
                this.$message.error(
                  res.message || (this.isEdit ? '编辑失败' : '新增失败')
                )
              }
            })
            .catch(error => {
              console.error(
                this.isEdit ? '更新订单失败' : '新增订单失败',
                error
              )
              this.$message.error(this.isEdit ? '更新订单失败' : '新增订单失败')
            })
            .finally(() => {
              this.loading = false
            })
        } else {
          return false
        }
      })
    },
    // 重置表单
    resetForm() {
      this.$refs.orderForm.resetFields()
      if (this.isEdit) {
        this.fetchOrderDetail(this.form.id)
      } else {
        this.form.products = []
      }
    },
    // 显示添加商品弹窗
    showAddProductDialog() {
      this.productForm = {
        productId: '',
        skuId: '',
        quantity: 1,
      }
      this.dialogVisible = true
    },
    // 获取最大可购买数量
    getMaxQuantity() {
      if (this.selectedSku) {
        return this.selectedSku.availableStock
      } else if (this.selectedProduct) {
        return this.selectedProduct.availableStock || this.selectedProduct.stock
      }
      return 999
    },

    // 将规格对象转换为文本
    skuSpecsToText(specs) {
      if (!specs) return ''
      return Object.entries(specs)
        .map(([key, value]) => `${key}: ${value}`)
        .join(', ')
    },

    // 选择商品变更
    handleDialogProductChange(productId) {
      this.selectedProduct =
        this.productOptions.find(item => item.value === productId)?.data || null
      this.selectedSku = null
      this.productForm.skuId = ''

      // 如果没有SKU，直接使用商品的价格
      if (
        !this.selectedProduct ||
        !this.selectedProduct.skus ||
        this.selectedProduct.skus.length === 0
      ) {
        this.productForm.price = this.selectedProduct?.price || 0
      }
    },

    // 选择SKU变更
    handleSkuChange(skuId) {
      if (!this.selectedProduct || !this.selectedProduct.skus) return

      this.selectedSku = this.selectedProduct.skus.find(sku => sku.id === skuId)
      if (this.selectedSku) {
        this.productForm.price = this.selectedSku.price

        // 限制数量不超过库存
        if (this.productForm.quantity > this.selectedSku.availableStock) {
          this.productForm.quantity = this.selectedSku.availableStock
        }
      }
    },

    // 确认添加商品
    confirmAddProduct() {
      if (!this.productForm.productId) {
        this.$message.error('请选择商品')
        return
      }

      // 检查库存
      const maxQuantity = this.getMaxQuantity()
      if (this.productForm.quantity > maxQuantity) {
        this.$message.error(`库存不足，最多可购买 ${maxQuantity} 件`)
        return
      }

      const selectedProduct = this.productOptions.find(
        item => item.value === this.productForm.productId
      )

      if (!selectedProduct) {
        this.$message.error('选择的商品不存在')
        return
      }

      let price = selectedProduct.data.price
      let skuSpecs = null

      // 如果选择了SKU
      if (this.selectedSku) {
        price = this.selectedSku.price
        skuSpecs = this.selectedSku.specs
      }

      const newProduct = {
        productId: this.productForm.productId,
        productName: selectedProduct.label,
        quantity: this.productForm.quantity,
        points: price,
        totalPoints: price * this.productForm.quantity,
      }

      // 如果有SKU
      if (this.productForm.skuId && this.selectedSku) {
        newProduct.skuId = this.productForm.skuId
        newProduct.skuSpecs = skuSpecs
      }

      this.form.products.push(newProduct)
      this.dialogVisible = false

      // 重置表单
      this.productForm = {
        productId: '',
        skuId: '',
        quantity: 1,
      }
      this.selectedProduct = null
      this.selectedSku = null
    },
    // 移除商品
    removeProduct(index) {
      this.form.products.splice(index, 1)
    },
    // 计算订单总积分
    calculateOrderTotal() {
      return this.form.products.reduce(
        (total, item) => total + item.totalPoints,
        0
      )
    },
    // 获取订单详情
    fetchOrderDetail(id) {
      this.loading = true
      getOrderDetail(id)
        .then(res => {
          if (res.code === 200 && res.data) {
            const orderData = res.data

            // 填充表单数据
            this.form = {
              id: orderData.id,
              orderNo: orderData.orderNo,
              createTime: orderData.createdAt,
              userId: orderData.userId,
              username: orderData.user ? orderData.user.username : '',
              status: orderData.status,
              receiver: orderData.receiver,
              phone: orderData.phone,
              address: orderData.address,
              remark: orderData.remark || '',
              products: orderData.items
                ? orderData.items.map(item => ({
                    productId: item.productId,
                    productName: item.productName,
                    quantity: item.quantity,
                    points: item.points,
                    totalPoints: item.totalPoints,
                  }))
                : [],
            }
          } else {
            this.$message.error(res.message || '获取订单详情失败')
            this.$router.push('/order/list')
          }
        })
        .catch(error => {
          console.error('获取订单详情出错', error)
          this.$message.error('获取订单详情失败')
          this.$router.push('/order/list')
        })
        .finally(() => {
          this.loading = false
        })
    },
  },
}
</script>

<style scoped>
.order-add-container {
  padding: 24px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: #ffffff;
  border-radius: 8px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

.content-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.section-card {
  background: #ffffff;
  padding: 24px;
  border-radius: 8px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e5e6eb;
}

.section-header h3 {
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

.product-list {
  margin-top: 16px;
}

.order-total {
  margin-top: 24px;
  text-align: right;
  font-size: 16px;
}

.total-points {
  color: #f56c6c;
  font-weight: bold;
  font-size: 18px;
}

.bottom-actions {
  margin-top: 24px;
  text-align: center;
}

.user-id {
  float: right;
  color: #909399;
  font-size: 13px;
}

.product-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.product-points {
  color: #f56c6c;
  font-weight: bold;
}

.sku-specs {
  margin-top: 5px;
  font-size: 12px;
}
.stock-info {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style> 